import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "../store/index";
import { getToken } from "@/utils/auth";
import router from "@/router";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, //URL地址   环境变量文件 .env.development
  // timeout: 5000, //超时
  withCredentials: true, //跨域时若要发生cookie,需要设置该选项
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      // 设置令牌请求头
      config.headers["token"] = getToken();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
let tokenAbnormal = false;
// 相应拦截
service.interceptors.response.use(
  // 通过自定义code 判定响应状态 也可以通过HTTP状态码判断
  (response) => {
    const res = response.data;
    // console.log(response)
    if (response.request.responseType == "blob" && response.status == 200) {
      return response;
    } else {
      // code 不为0 则判断为一个错误
      if (res.code != 200) {
        // 假设 10008 非法令牌  10012 其他客户端已经登陆
        if (res.code == 403) {
          // 重新登陆
          if (!tokenAbnormal) {
            tokenAbnormal = true;
            Message({
              message: res.msg || "Error",
              type: "error",
            });
            setTimeout(() => {
              tokenAbnormal = false;
            }, 3000);
          }
          sessionStorage.setItem("address", null);
          sessionStorage.setItem("Token", "");
          router.push("/login");
        } else {
          Message({
            message: res.msg || "Error",
            type: "error",
            duration: 5 * 1000,
          });
        }

        return Promise.reject(new Error(res.message || "Error"));
      } else {
        return res;
      }
    }
  },
  (error) => {
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
  }
);

export default service;
